import { Message } from 'element-ui'
import {
  queryCommonStationUnitsInfo,
  download,
  addConventionalUnit,
  downloadCommonStationUnit,
  deleteCommonStationUnit,
} from '@/api/conventionalUnit.js'
import { getPdf } from '@/api/windPower.js'
import { regulationOrgList, stationTypeLists } from '@/api/dict.js'
import testResultEdit from '@/views/testResult/testResultEdit/testResultEdit.vue'
//引入VueOfficePdf组件
import * as XLSX from 'xlsx'

export default {
  components: { testResultEdit },
  name: 'conventionalUnit',
  data() {
    let yesOrNoList = {
      0: '否',
      1: '是',
    }
    return {
      formData: new FormData(), //载体
      queryCommonStationUnitsInfo,
      pdf: '', //设置文档地址
      getFrom: {
        companyId:''
      }, //每行的数据
      addDialogVisibleTitle: '新增',
      queryDetailParam: {
        regulationOrgId: '',
        stationType: '',
        stationName: '',
        singleCapStart: null,
        singleCapEnd: null,
        companyName: '',
      },
      tableData: [], //每页的表格数据,
      operate: 'add',
      id: 0,
      dispatchList: [], //调度
      stationTypeLists: [], //类型
      // 预览弹框
      dialogPreVisible: false,
      headList: [
        {
          name: '所属调度',
          value: 'regulationOrgName',
          noSort: true,
        },
        { name: '类型', value: 'stationTypeName', noSort: true },
        { 
          // name: '场站名称', 
          name: '电厂名称', 
        value: 'stationName', noSort: true },
        {
          name: '单机容量',
          value: 'singleMachineCap',
          noSort: true,
          formatter: (row) => (row.singleMachineCap ? `${row.singleMachineCap}MW` : ''),
        },
        { name: '机组编号', value: 'unitsNumber', noSort: true },
        { name: '产权单位', value: 'companyName', noSort: true },
        {
          // name: '一次调频实验方案',
          name: '快速频率响应试验方案',
          value: 'regulationTestPlan',
          order: 'regulationTestPlanId',
          noSort: true,
          type: 'linkPreview',
          type1:'upload',
          clickPreview: this.doPreview,
          clickDownload: this.doDownload,
          clickUpload:this.doUpload
        },
        {
          // name: '实验方案上传时间',
          name: '上传时间',
          value: 'regulationTime1',
          noSort: true,
          formatter: (row) => (row.regulationTestPlan ? row.regulationTestPlan.createTime.replace('T', ' ') : ''),
        },
        {
          name: '审核通过',
          value: 'caseIsAudited',
          noSort: true,
          fontColor: true,
          formatter: (row) => (yesOrNoList[row.caseIsAudited] ? yesOrNoList[row.caseIsAudited] : ''),
        },
        {
          name: '审核时间',
          value: 'caseIsAudited',
          noSort: true,
          formatter: (row) => (row.caseIsAudited ? row.caseIsAudited.replace('T', ' ') : ''),
        },
        {
          // name: '一次调频测试报告',
          name: '快速频率响应测试报告',
          value: 'regulationTestReport',
          order: 'regulationTestReportId',
          noSort: true,
          type: 'linkPreview',
          clickPreview: this.doPreview,
          clickDownload: this.doDownload,
        },
        {
          // name: '测试报告上传时间',
          name: '上传时间',
          value: 'regulationTime3',
          noSort: true,
          formatter: (row) => (row.regulationTestReport ? row.regulationTestReport.createTime.replace('T', ' ') : ''),
        },
        {
          name: '审核通过',
          value: 'reportIsAudited',
          noSort: true,
          fontColor: true,
          formatter: (row) => (yesOrNoList[row.reportIsAudited] ? yesOrNoList[row.reportIsAudited] : ''),
        },
        {
          name: '审核时间',
          value: 'reportAuditTime',
          noSort: true,
          formatter: (row) => (row.reportAuditTime ? row.reportAuditTime.replace('T', ' ') : ''),
        },
        { name: '主动测试次数', value: 'activeTestNum', noSort: true },
        { name: '合格次数', value: 'qualifiedNum', noSort: true },
        { name: '合格率', value: 'qualifiedRatio', noSort: true },
        {
          name: '主动测试结果',
          value: 'result',
          noSort: true,
          type: 'check',
          clickCheck:this.doCheck
        },
        // {
        //   name: '一次调频定值单',
        //   value: 'regulationReportForm',
        //   order: 'regulationReportFormId',
        //   noSort: true,
        //   type: 'linkPreview',
        //   clickPreview: this.doPreview,
        //   clickDownload: this.doDownload,
        // },
        // {
        //   name: '定值单上传时间',
        //   value: 'regulationTime2',
        //   noSort: true,
        //   formatter: (row) => (row.regulationReportForm ? row.regulationReportForm.createTime.replace('T', ' ') : ''),
        // },
        // {
        //   name: '是否滞后',
        //   value: 'isDelay',
        //   noSort: true,
        //   fontColor: true,
        //   formatter: (row) => (yesOrNoList[row.isDelay] ? yesOrNoList[row.isDelay] : ''),
        // },
       
      ],
      // 新增弹框显示
      dialogFormVisible: false,
      formLabelWidth: '120px',
    }
  },
  mounted() {
    // this.fetchData();
  },
  created() {
    this.regulationOrgList()
    this.stationTypeList()
  },

  computed: {},
  methods: {
    // 新增弹框
    addWindPower() {
      this.id++
      this.addDialogVisibleTitle = '新增'
      this.dialogFormVisible = true
      ;(this.operate = 'add'), (this.getFrom = { regulationOrgId: '1', stationType: '1' })
    },
    // 获取表格多行选中的数据
    getMultipleSelection() {
      this.tableData = JSON.parse(JSON.stringify(this.$refs.conventionalUnitTable.multipleSelection))

      this.tableData.forEach((element) => {
        this.getFrom = element
      })
    },
    // 编辑
    editWindPower() {
      this.operate = 'edit'
      this.getMultipleSelection()
      if (this.tableData && this.tableData.length < 1) {
        Message.warning('请先勾选要编辑的数据')
      } else if (this.tableData && this.tableData.length > 1) {
        Message.warning('编辑的时候只能选择一条数据,请重新选择')
        return false
      } else {
        this.addDialogVisibleTitle = '编辑'
        this.dialogFormVisible = true
        return true
      }
    },

    // 复制
    copyWindPower() {
      this.operate = 'copy'
      this.getMultipleSelection()
      if (this.tableData && this.tableData.length < 1) {
        Message.warning('请先勾选要复制的数据')
      } else if (this.tableData && this.tableData.length > 1) {
        Message.warning('复制的时候只能选择一条数据,请重新选择')
        return false
      } else {
        this.addDialogVisibleTitle = '复制'
        // 复制的时候清空所有的文件上传
        this.getFrom.regulationReportForm = ''
        this.getFrom.regulationTestPlan = ''
        this.getFrom.regulationTestReport = ''
        // this.getFrom.responsePlan = "";
        // this.getFrom.responseReport = "";
        this.dialogFormVisible = true
        return true
      }
    },

    // 删除
    deleteWindPower() {
      if (this.$refs.conventionalUnitTable.multipleSelection.length === 0) {
        Message.warning('请选择要删除的数据')
        return
      }
      // 确认删除嘛
      this.$confirm('是否确认删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          let params = this.$refs.conventionalUnitTable.multipleSelection.map((item) => item.unitsId)
          // 发送请求
          deleteCommonStationUnit(params).then((res) => {
            if (res.code === '000000') {
              Message.success('删除成功')
              this.$refs.conventionalUnitTable.getDataInit()
            }
          })
        })
        .catch(() => {
          Message.info('已取消删除')
        })
    },
    // 检索
    searchList() {
      this.$refs.conventionalUnitTable.getDataInit()
    },
    // 检索重置
    resetSearchList() {
      for (let key in this.queryDetailParam) {
        this.queryDetailParam[key] = ''
      }
      this.$refs.conventionalUnitTable.getDataInit()
    },

    // 详情重置
    resetCon() {
      this.getFrom = {}
      if (this.$refs.childRules.$refs.station) {
        this.$refs.childRules.$refs.station.labels = ''
      }
      if (this.$refs.childRules.$refs.company) {
        this.$refs.childRules.$refs.company.labels = ''
      }
    },

    // 保存
    saveForm() {
      // 校验
      let flag = this.$refs['childRules'].validateForm()

      if (!this.$refs.childRules.$refs.station.labels) {
        Message.error('请选择场站名称')
        return false
      }
      if (!this.$refs.childRules.$refs.company.labels) {
        Message.error('请选择产权单位')
        return false
      }
      if (flag) {
        this.addConventionalUnit()
      } else {
        return
      }
    },

    // 首先封装参数（对象）转换为formData格式
    getFormData(object) {
      let form = this.$refs.childRules
      // 文件存在就append,不存在就不append,不往后台传递这个字段
      form.fileList1[0] && this.formData.set('regulationReportForm', form.fileList1[0].raw)
      form.fileList2[0] && this.formData.set('regulationTestPlan', form.fileList2[0].raw)
      form.fileList3[0] && this.formData.set('regulationTestReport', form.fileList3[0].raw)
      // form.fileList4[0] &&
      //   this.formData.set("responsePlan", form.fileList4[0].raw);
      // form.fileList5[0] &&
      //   this.formData.set("responseReport", form.fileList5[0].raw);
      this.formData.set('unitsNumber', this.getFrom.unitsNumber)
      this.getFrom.regulationOrgId && this.formData.set('regulationOrgId', this.getFrom.regulationOrgId)
      this.getFrom.stationType && this.formData.set('stationType', this.getFrom.stationType)
      this.getFrom.singleMachineCap && this.formData.set('singleMachineCap', this.getFrom.singleMachineCap)
      //台数存在就append,不存在就不append/set,不往后台传递字段
      this.getFrom.machineNum && this.formData.set('machineNum', this.getFrom.machineNum)
      this.getFrom.unitsTotalCap && this.formData.set('unitsTotalCap', this.getFrom.unitsTotalCap)

      // 区分编辑还是新增
      if (this.operate === 'add' || this.operate === 'copy') {
        this.formData.set('operateCode', '1')
      }
      if (this.operate === 'edit') {
        this.formData.set('operateCode', '2')
        this.formData.set('unitsId', this.$refs.conventionalUnitTable.multipleSelection[0].unitsId)
        this.formData.set('regulationId', this.$refs.conventionalUnitTable.multipleSelection[0].regulationId)
      }

      return this.formData
    },

    // 新增接口
    async addConventionalUnit() {
      // 在getFormData()方法里面写，取不到his.$refs.childRules.$refs.station值（因为异步，所以写在接口里）
      this.formData = this.getFormData()
      this.formData.set('stationId', this.$refs.childRules.$refs.station.labels)
      //this.formData.set('stationName', this.$refs.childRules.$refs.station.stationName)
      // this.formData.set('companyName', this.$refs.childRules.$refs.company.labels)
      this.formData.set('companyId', this.$refs.childRules.$refs.company.labels)
      await addConventionalUnit(this.formData).then((res) => {
        if (res.code === '000000') {
          Message.success(`${this.addDialogVisibleTitle}成功`)
          // 刷新列表的操作  getDataInit():组件的内置方法,用于刷新列表接口
          this.$refs.conventionalUnitTable.getDataInit()
          this.dialogFormVisible = false
        }
      })
      // .catch((err) => {
      //   Message.error(`${this.addDialogVisibleTitle}失败`);
      // });
    },

    // 导出
    async downloadCon() {
      let excelName = '常规机组列表.xlsx'
      const res = await downloadCommonStationUnit(this.queryDetailParam)
      const link = document.createElement('a')
      let blob = new Blob([res], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      })
      link.style.display = 'none'
      link.href = URL.createObjectURL(blob)
      link.download = excelName //下载的文件名
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },

    //  导出
    exportExcel() {
      this.downloadCon()
    },

    // 总调下拉框的数据
    async regulationOrgList() {
      await regulationOrgList().then((res) => {
        if (res.code === '000000') {
          this.dispatchList = res.data
        }
      })
    },

    // 场站类型下拉框的数据
    async stationTypeList() {
      await stationTypeLists().then((res) => {
        if (res.code === '000000') {
          this.stationTypeLists = res.data
        }
      })
    },
    // 预览
    async doPreview(row, col) {
      const res = await getPdf(row[`${col}Id`])
      if (res.fileType !== 'pdf' && res.fileType !== 'xlsx' && res.fileType !== 'xls') {
        this.$message.warning('只支持pdf与excel格式的文件预览')
        return
      }
      let typeList = {
        pdf: 'application/pdf',
        xls: 'application/vnd.ms-excel',
        xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      }
      const blob = new Blob([res], { type: typeList[res.fileType] })
      if (res.fileType === 'pdf') {
        this.pdf = URL.createObjectURL(blob)
      } else {
        const reader = new FileReader()
        reader.onload = (e) => {
          const data = new Uint8Array(e.target.result)
          let workbook = XLSX.read(data, { type: 'array' }) // 解析数据
          this.tableToHtml(workbook)
        }
        reader.readAsArrayBuffer(blob)
      }
      this.dialogPreVisible = true
    },
    tableToHtml(workbook) {
      var worksheet = workbook.Sheets[workbook.SheetNames[0]]
      // var innerHTML = XLSX.utils.sheet_to_html(worksheet);
      if (document.querySelector('#tableHtml')) {
        document.querySelector('#tableHtml').innerHTML = XLSX.utils.sheet_to_html(worksheet)
        document.querySelector('.table-html-wrap table')
        let trs = document.querySelectorAll('tr')
        trs.forEach((tr) => {
          if (!tr.innerText.trim()) {
            tr.remove()
          }
        })
        document.querySelector('.el-dialog__body').style.overflowX = 'auto'
      }
      let tds = document.querySelectorAll('td')
    },
    // 下载
    async doDownload(row, col, name) {
      let excelName = `${name}`
      const res = await getPdf(row[`${col}Id`])
      if (res.fileType !== 'pdf' && res.fileType !== 'xlsx' && res.fileType !== 'xls') {
        this.$message.warning('只支持pdf与excel格式的文件下载')
        return
      }
      let typeList = {
        pdf: 'application/pdf',
        xls: 'application/vnd.ms-excel',
        xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      }
      const link = document.createElement('a')
      let blob = new Blob([res], {
        type: typeList[res.fileType],
      })
      // xlsx的文件type

      link.style.display = 'none'
      link.href = URL.createObjectURL(blob)
      link.download = excelName //下载的文件名
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },

    async downloadWin() {
      let excelName = '导出常规机组列表.xlsx'
      const res = await downloadCommonStationWin(this.queryDetailParam)
      const link = document.createElement('a')
      let blob = new Blob([res], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      })
      link.style.display = 'none'
      link.href = URL.createObjectURL(blob)
      link.download = excelName //下载的文件名
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },

    // 列表上传
    doUpload(){
      //
    },

    //列表查看，跳转到新型资源快速频率响应主动测试页面
    doCheck(){
      this.$router.push({ path: '/windPower', query: { stationId: '001' } })
      console.log(this.$route.path,'222')
      // this.$router.push({ name: 'home', params: { id: '001' } })  
    }

  },
}
